package cn.itcast.bos.web.action.take_delivery;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.domain.take_delivery.WayBill;
import cn.itcast.bos.service.take_delivery.WayBillService;
import cn.itcast.bos.web.action.commom.BaseAction;

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class WayBillAction extends BaseAction<WayBill> {
	@Autowired
	private WayBillService wayBillService;
	//记录日志
	private static final Logger LOGGER = Logger.getLogger(WayBill.class);

	 @Action(value = "waybill_save", results = {
			@Result(name = "success", type = "json") }) 
	public String save(){
		 Map<String,Object> map = new HashMap<String,Object>();
		 try{
			 //waybill对象关联一个没有id的order对象会报异常
			 if(model.getOrder()!=null&&
					 (model.getOrder().getId()==null||model.getOrder().getId()==0)){
				 model.setOrder(null);
			 }
			 wayBillService.save(model);
			 map.put("success",true);
			 map.put("msg","保存运单成功");
			 LOGGER.info("保存运单成功,运单号"+model.getWayBillNum());
		 }catch(Exception e){
			 e.printStackTrace();
			 map.put("success",false);
			 map.put("msg","保存运单失败");
			 LOGGER.error("保存运单成功,运单号"+model.getWayBillNum(),e);
		 }
		 ServletActionContext.getContext().getValueStack().push(map);
		 
		return SUCCESS;
	}
	 
	 
	 
	 @Action(value = "waybill_pageQuery", results = {
				@Result(name = "success", type = "json") }) 
	 public String pageQuery(){

		Pageable pageable = new  PageRequest(page-1,rows,new Sort(new Sort.Order(Sort.Direction.DESC, "id")));
		Page<WayBill> pageData = wayBillService.findPageData(model,pageable);
		pushPageDataToValueStack(pageData);
		 return SUCCESS;
	 }
	 
	 
	 
	 @Action(value = "waybill_findByWaybillNum", results = {
			 @Result(name = "success", type = "json") }) 
	 public String findByWaybillNum(){
		WayBill wayBill =  wayBillService.findByWaybillNum(model.getWayBillNum());
		Map<String,Object> map = new HashMap<String,Object>();
		if (wayBill==null) {
			map.put("succcess", false);
		}else{
			map.put("success", true);
			map.put("wayBillData", wayBill);
		}
		ServletActionContext.getContext().getValueStack().push(map);
		 return SUCCESS;
	 }
	 
	 
	
}
